package com.example.file_management.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.file_management.mapper.material",sqlSessionFactoryRef = "materialSqlSessionFactory")
public class MaterialDBConfig {
    @Primary
    @Bean(name = "materialDataSource")
    @ConfigurationProperties("spring.datasource.material")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "materialSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("materialDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mybatis/material/*.xml"));
        // 设置 MyBatis 的配置属性
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
//        configuration.getTypeHandlerRegistry().registerAll(com.example.file_management.typehandlers.TaskIdTypeHandler.class);
        configuration.getTypeAliasRegistry().registerAliases("com.example.file_management.pojo.material");

        sessionFactoryBean.setConfiguration(configuration);

        return sessionFactoryBean.getObject();
    }
}
